<script setup lang="ts">
import {CrowdLabelInterface} from "~/contentScripts/views/wxt/BatchAddingProducts/components/Crowd/CrowdInterface";
import {WxtBizCode, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";

const props = defineProps({
  value: {
    type: Boolean,
    default: false,
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
  materialIdList: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
  campaignId: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
  recSceneList: {
    type: Array as PropType<string[]>,
    default: () => ['recSceneNew'],
  },
  topicId: {
    type: Number,
    default: 79,
  },
  tabs: {
    type: Array as PropType<any[]>,
    default: () => [],
  },
  labelList: {
    type: Array as PropType<string[]>,
    default: () => [
      {
        labelId: '3000525',
      }
    ],
  },
});
const emit = defineEmits([
  "update:value",
]);
const crowd = ref<CrowdLabelInterface[]>([]);
const loadData = (index: number = -1) => {
  let topicId: any = '';
  let labelList: any[] = [];
  if (index === -1) {
    topicId = props.topicId;
    labelList = props.labelList;
  } else {
    topicId = props.tabs[index].topicId;
    labelList = props.tabs[index].labelList;
  }
  isLoading.value = true;
  WxtUtils.customFormRequest('https://dmp-gateway.alimama.com/api/dmp/crowd/topic/template', props.bizCode, {
    topicSceneType: 2,
    appCode: 'dmpPlatformFeatured',
    properties: {},
    campaignId: props.campaignId,
    promotionType: 'item',
    subPromotionType: 'item',
    subPromotionTypeList: ['item'],
    wordList: [],
    wordPackageList: [],
    materialIdList: props.materialIdList,
    topicId: topicId,
  }).then((res: any) => {
        if (res.data.info.ok) {
          WxtUtils.customFormRequest('https://dmp-gateway.alimama.com/api/dmp/crowd/applyJxTemplate.json', props.bizCode, {
            topicSceneType: 2,
            appCode: 'dmpPlatformFeatured',
            materialIdList: props.materialIdList,
            campaignId: props.campaignId,
            promotionType: 'item',
            subPromotionType: 'item',
            subPromotionTypeList: ['item'],
            topicId: topicId,
            templateBaseInfoList: res.data.data.result.map((item: any) => {
              return {
                topicId: topicId,
                templateId: item.templateId,
                templateRuleFilling: null,
              }
            }),
          }).then(result => {
            if (res.data.data.result.length === 0) {
              crowd.value = [];
              isLoading.value = false;
            } else {
              WxtUtils.customRequest('https://one.alimama.com/label/dmpConvert.json', props.bizCode, {
                    bizCode: props.bizCode,
                    crowdList: res.data.data.result.map((item: any, key: number) => {
                      return {
                        labelList: labelList,
                        optionList: [
                          {
                            optionName: item.templateName,
                            optionValue: result.data.data.result[key].dmpCrowdId + '',
                            templateId: item.templateId,
                            topicId: topicId,
                          }
                        ],
                      }
                    })
                  },
              ).then((res2: any) => {
                crowd.value = res2.data.data.list;
                isLoading.value = false;
              });
            }
          });
        }
      }
  );
};
const isLoading = ref(false);
const state = reactive<any>({
  selectedAll: false,
  indeterminate: false,
  selectedCrowd: [],
});
watch(() => state.selectedCrowd, (val) => {
  if (val.length === crowd.value.length) {
    state.selectedAll = true;
    state.indeterminate = false;
  } else if (val.length === 0) {
    state.selectedAll = false;
    state.indeterminate = false;
  } else {
    state.selectedAll = false;
    state.indeterminate = true;
  }
  emit('update:value', val.map((item: any) => {
    return crowd.value.find((it: any) => it.optionList[0].optionValue === item);
  }));
}, {
  deep: true,
});
const tabData = ref<any[]>(props.tabs.map((item: any) => {
  return {
    ...item,
    value: [],
  }
}));
watch(() => props.tabs, (val) => {
  // 将所有tab下value合并
  tabData.value = val.map((item: any) => {
    return {
      ...item,
      value: [],
    }
  });
}, {
  deep: true,
});
const toggleSelectedAll = (val: { target: { checked: boolean; }; }) => {
  if (val.target.checked) {
    state.selectedCrowd = crowd.value.map((item: any) => item.optionList[0].optionValue);
  } else {
    state.selectedCrowd = [];
  }
}
if (props.tabs.length > 0) {
  loadData(0);
} else {
  loadData();
}
watch(() => tabData.value, (val) => {
  // 将所有tab下value合并
  let allValue: any[] = [];
  val.forEach((item: any) => {
    allValue = allValue.concat(item.value);
  });
  emit('update:value', allValue);
}, {
  deep: true,
});
// loadData();
</script>

<template>
  <template v-if="tabs.length===0">
    <div v-if="crowd.length>0">
      <a-checkbox :checked="state.selectedAll" :indeterminate="state.indeterminate" @change="toggleSelectedAll">全选
      </a-checkbox>
      <a-divider style="margin: 10px 0;"/>
      <a-checkbox-group v-model:value="state.selectedCrowd" style="display: block">
        <a-row type="flex" v-for="item in crowd">
          <a-checkbox :key="item.labelId" :value="item.optionList[0].optionValue">{{ item.optionList[0].optionName }}
          </a-checkbox>
        </a-row>
      </a-checkbox-group>
    </div>
    <template v-if="isLoading">
      <div style="text-align: center;padding-top: 50px;">
        <a-spin/>
      </div>
    </template>
    <template v-else-if="crowd.length===0">
      <div style="text-align: center;padding-top: 50px;">
        <a-empty description="暂无数据"/>
      </div>
    </template>
  </template>
  <template v-else>
    <a-tabs size="small" style="margin-top: -10px;">
      <a-tab-pane v-for="(tab, index) in tabData" :key="index" :tab="tab.title">
        <CrowdTopicTemplatePanel :labelList="tab.labelList" :topicId="tab.topicId" :bizCode="bizCode"
                                 :materialIdList="materialIdList"
                                 :campaignId="campaignId" :recSceneList="recSceneList" v-model:value="tab.value"
        />
      </a-tab-pane>
    </a-tabs>
  </template>
</template>

<style scoped>

</style>
